import Crypto from './crypto'
import hmacsha1 from 'hmacsha1'

const config = {
  secretKey: 'QZomTs1tUose9NK2TcU6RVIp54lBLEqA',
  secretId: 'AKIDwhBQO5VeX9UYMt98rKWS7WeV5PSEiwtZ',
  appId: 1305176425,
}

/**
 * 获取签名
 * @param wordArray
 * @returns
 */
export function toUint8Array(wordArray: { words: LooseObject[], sigBytes: number }) {
  const { words, sigBytes } = wordArray
  const uint8Array = new Uint8Array(sigBytes)
  for (let i = 0; i < sigBytes; i++) {
    uint8Array[i] = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff
  }
  return uint8Array
}

/**
 * @param fileData
 * @returns
 */
export function Uint8ArrayToString(fileData: LooseObject) {
  let dataString = ''
  for (let i = 0; i < fileData.length; i++) {
    dataString += String.fromCharCode(fileData[i])
  }
  return dataString
}

/**
 * 签名函数
 * @param sign
 * @returns
 */
export function signCallback(sign: string) {
  const secretKey = config.secretKey
  const hash = Crypto.HmacSHA1(sign, secretKey)
  const bytes = Uint8ArrayToString(toUint8Array(hash))
  return window.btoa(bytes)
}

export function fitAsrText(text: string) {
  const keyWordsFitMap = {
    '公墓': '公募',
    '武林': '五零',
    '公务': '公募',
    '五零': '50',
    'V': '微',
    '公母': '公募',
    '公布': '公募',
    '公路': '公募',
    '公共零': '公募50',
    '公募林': '公募50',
    '五年': '50',
    '松木': '公募',
    '公共50': '公募50',
    '公共五零': '公募50',
    '污泥': '50',
    '武尼': '50',
    '公募尼': '公募50',
    '原宇宙': '元宇宙',
    '圆宇宙': '元宇宙',
    'for': 'FOF',
    '功夫': '共富',
    '食堂': '学堂',
    '共富学法': '共富学堂',
    '公木林': '公募50',
    '共埠学堂': '共富学堂',
    '公募零': '公募50',
    '公共林': '公募50'
  }
  for (let fit in keyWordsFitMap) {
    text = text.replaceAll(fit, keyWordsFitMap[fit])
  }
  return text
}

export function uuid() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    const r = (Math.random() * 16) | 0,
      v = c === 'x' ? r : (r & 0x3) | 0x8
    return v.toString(16)
  })
}

export function getSignature(key: string, data: string): string {
  return hmacsha1(key, data)
}
